package mspbots.data.tl.prod.contactscience.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultMessageModel;
import mspbots.data.tl.prod.contactscience.mapper.ContactscienceAppointmentsMapper;
import mspbots.data.tl.prod.contactscience.model.ContactscienceAppointments;
import mspbots.data.tl.prod.contactscience.service.ContactscienceAppointmentsService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;

/**
 * @author Jay.Yang
 */

@Service
@Log4j2
@DS("master")
public class ContactscienceAppointmentsServiceImpl extends AbstractBaseServiceImpl<ContactscienceAppointmentsMapper, ContactscienceAppointments>
        implements ContactscienceAppointmentsService {

    private SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy KK:mmaa", Locale.ENGLISH);
    private SimpleDateFormat sdf1 = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss", Locale.ENGLISH);

    @Override
    public void sync(ResultMessageModel model) {
        if (ObjectUtils.isEmpty(model.getEntity()) || !ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            log.error("contactscience.appointments.tl entry is null,or Action No Add");
            return;
        }
        Iterator<JsonNode> setAppointments = model.getEntity().get("setAppointments").elements();
        Iterator<JsonNode> scheduledAppointments = model.getEntity().get("scheduledAppointments").elements();
        while (setAppointments.hasNext()){
            processData(model, setAppointments,"setAppointments");
        }
        while (scheduledAppointments.hasNext()){
            processData(model, scheduledAppointments,"scheduledAppointments");
        }
    }

    private void processData(ResultMessageModel model, Iterator<JsonNode> appointments,String type) {
        JsonNode node = appointments.next();
        ContactscienceAppointments data = ContactscienceAppointments.builder()
                .owner(model.getEntity().get("owner").asText())
                .ccId(node.get("id").asLong())
                .setBy(node.get("setBy").asText())
                .dateSet(processDate(node.get("dateSet").asText()))
                .comments(node.get("comments").asText())
                .lastChange(processDate(node.get("lastChange").asText()))
                .suspectZip(node.get("suspectZIP").asText())
                .suspectCity(node.get("suspectCity").asText())
                .suspectName(node.get("suspectName").asText())
                .suspectState(node.get("suspectState").asText())
                .suspectStreet(node.get("suspectStreet").asText())
                .suspectContact(node.get("suspectContact").asText())
                .appointmentDate(processDate(node.get("appointmentDate").asText()))
                .suspectOrganization(node.get("suspectOrganization").asText())
                .syncTime(LocalDateTime.now())
                .type(type)
                .build();
        data.setTenantCode(model.getTenantId());

        ContactscienceAppointments dbData = super.baseMapper.selectOne(Wrappers.<ContactscienceAppointments>lambdaQuery()
                .eq(ContactscienceAppointments::getTenantCode, data.getTenantCode())
                .eq(ContactscienceAppointments::getCcId, data.getCcId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }
    }

    private LocalDateTime processDate(String date) {
        try {
            if (StringUtils.isEmpty(date)) {
                return null;
            }
            Date d2 = sdf.parse(date);
            String lastChange = sdf1.format(d2).replace(" ", "T").replaceFirst("0", "2");
            return LocalDateTime.parse(lastChange, DateTimeFormatter.ISO_DATE_TIME);
        } catch (ParseException e) {
            log.error(e.getMessage());
            return null;
        }
    }
}
